<template>
  <div class="sc-wrap">
    <router-view></router-view>
  </div>
</template>
<script type="text/javascript">
/**
 * sc，在这里做一些数据初始化的准备工作
 */
import api from '../common/js/api';
import { mapGetters } from 'vuex';
import vpJson from '../view-id-page';

const getDevices = (params, includeFields) => {
  return api.post(`resourceUIService.getDevicesByCondition${includeFields ? '?includeFields=label,category,customerId,externalDevId,id,values.images,domains,modelId' : ''}`, params).then(ret => {
    return ret;
  });
};
const getResourcesByModelId = (modelId, includeFields) => {
  return api.post(`resourceUIService.getResourceByModelId${includeFields ? '?includeFields=parentID,category,modelId,label,id,values.number,values.longitude,values.latitude,domainPath,domainControlled' : ''}`, modelId).then(ret => {
    return ret;
  });
};

/**
 * 获取当前用户
 * @returns {Q.Promise<any> | * | PromiseLike<any>}
 */
const getCurrentUser = () => {
  return api.post('userLoginUIService.getCurrentUser', []).then(ret => {
    return ret;
  });
};

/**
 * 获取企业配置
 * @returns {Q.Promise<any> | * | PromiseLike<any>}
 */
const getEnterPriseConfig = () => {
  return api.post('configUIService.getConfigsByGroupName', 'EnterpriseConfig').then(ret => {
    return ret;
  });
};

/**
 * 获取所有用户
 * @returns {Q.Promise<any> | * | PromiseLike<any>}
 */
const queryEnterpriseRole = () => {
  return api.post('userEnterpriseService.queryEnterpriseRole', null).then(ret => {
    return ret;
  });
};

/**
 * 获取所有字典
 * @returns {Q.Promise<any>|  * | PromiseLike</any>}
 */

const getAllDictionary = () => {
  return api.post('dictionaryService.getAllDicts', null).then(ret => ret);
};

/**
 * 通过用户的roleID获取用户当前的角色默认取第一个
 * @param currentUserRoleId
 * @returns {*|null}
 */
const getCurrentRoleId = (currentUserRoleId) => {
  let rs;
  if (typeof currentUserRoleId === 'string') {
    let localRoleId = localStorage.getItem('roleId');
    let roleIdArr = currentUserRoleId.split(',');
    if (roleIdArr.includes(localRoleId)) {
      rs = parseInt(localRoleId);
    } else {
      rs = parseInt(roleIdArr[0]);
    }
    return rs;
  }
  console.warn('角色ROLEID不为字符串');
  return null;
};

export default {
  name: 'ServiceCenter',
  data () {
    return {
      loading: true
    };
  },
  computed: {
    ...mapGetters('role', [
      'currentRole'
    ]),
    currentUser () {
      return this.$store.state.user.currentUser;
    }
  },
  mounted () {
    const loading = this.$loading({
      lock: true,
      text: '拼命加载中...',
      spinner: 'el-icon-loading',
      background: '#eeee'
    });
    Promise.all([
      getCurrentUser(),
      getEnterPriseConfig(),
      queryEnterpriseRole(),
      getAllDictionary()
    ]).then(ret => {
      let currentUser = ret[0].data;
      let enterpriseConfig = ret[1].data;
      let allRoles = ret[2].data;
      let allDictionary = ret[3].data;

      let currentRoleId = getCurrentRoleId(currentUser.roleID);
      currentUser.userCurrentRoleID = currentRoleId;
      localStorage.setItem('roleId', currentRoleId);

      this.$store.commit('user/setCurrentUser', currentUser);
      this.$store.commit('config/setEnterpriseConfig', enterpriseConfig);
      this.$store.commit('role/setAllRoles', allRoles);
      this.$store.commit('dictionary/setAllDictionary', allDictionary);

      let params = {};
      let currentRoleID = currentUser.userCurrentRoleID;
      let roleFunctionCodeMap = currentUser.roleFunctionCodeMap || {};
      let menuItems = roleFunctionCodeMap[currentRoleID] || [];
      let vals = (menuItems => {
        if (menuItems.indexOf('F08_01') !== -1) return {};
        if (menuItems.indexOf('F08_03') !== -1) return { diagnosticType: '90' };
        if (menuItems.indexOf('F08_06') !== -1) return { diagnosticType: '280' };
        if (menuItems.indexOf('F08_02') !== -1) return { diagnosticType: { NOT_IN: ['90', '280'] } };
      })(menuItems);
      params.values = vals;
      Promise.all([
        getResourcesByModelId(300, true),
        getResourcesByModelId(301, true),
        getResourcesByModelId(302, true),
        getDevices(params, true)
      ]).then(ret => {
        let domains = [...ret[0].data, ...ret[1].data, ...ret[2].data].filter(item => item.domainControlled);
        let devices = ret[3].data;
        this.$store.commit('resource/setDomains', domains);
        this.$store.commit('resource/setDevices', devices);
        loading.close();
        this.loading = false;
        if (this.$router.currentRoute.fullPath.indexOf('/app-sc/') === -1) {
          let currentRolePermission = JSON.parse(this.currentRole.values);
          let firstChild = currentRolePermission.children[0];
          if (firstChild.children && firstChild.children.length > 0) {
            console.error('error');
          } else {
            let viewId = vpJson[firstChild.viewId] || firstChild.viewId;
            this.$store.commit('resource/setCurrentResourceId', this.currentUser.domainIds);
            this.$router.push(`/app-sc/Main/${firstChild.showTree}/${this.currentUser.domainIds}/0/${viewId}`);
          }
        }
      });
    });
  }
};
</script>
<style lang="scss" scoped>
@keyframes validate-loading-spinner-animation {
  0% {
    transform: rotate(0);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.sc-wrap {
  height: 100%;
  width: 100%;
  position: relative;
}
</style>
